# coding=utf-8
from . import api
from app import util
from flask import request
import requests, json


# 返回简称
@api.route('/api/ip_info', methods=['post'])
def ip_info():
    data = {}
    data['code'] = 400
    data['data'] = ''
    try:
        ip = request.headers.get('X-Real-Ip', request.remote_addr)
        url = 'https://freeapi.ipip.net/' + str(ip)
        res = requests.get(url)
        content = json.loads(res.text)
        data['code'] = 200
        data['data'] = province_to_short(content[1])
    except Exception as e:
        print e
        data['code'] = 500
    return util.to_json(data)


def province_to_short(province):
    if province == "北京":
        return "京"
    elif province == "天津":
        return "津"
    elif province == "重庆":
        return "渝"
    elif province == "上海":
        return "沪"
    elif province == "河北":
        return "冀"
    elif province == "山西":
        return "晋"
    elif province == "辽宁":
        return "辽"
    elif province == "吉林":
        return "吉"
    elif province == "黑龙江":
        return "黑"
    elif province == "江苏":
        return "苏"
    elif province == "浙江":
        return "浙"
    elif province == "安徽":
        return "皖"
    elif province == "福建":
        return "闽"
    elif province == "江西":
        return "赣"
    elif province == "山东":
        return "鲁"
    elif province == "河南":
        return "豫"
    elif province == "湖北":
        return "鄂"
    elif province == "湖南":
        return "湘"
    elif province == "广东":
        return "粤"
    elif province == "海南":
        return "琼"
    elif province == "四川":
        return "川"
    elif province == "贵州":
        return "黔"
    elif province == "云南":
        return "云"
    elif province == "陕西":
        return "陕"
    elif province == "甘肃":
        return "甘"
    elif province == "青海":
        return "青"
    elif province == "台湾":
        return "台"
    elif province == "内蒙古":
        return "蒙"
    elif province == "广西":
        return "桂"
    elif province == "宁夏":
        return "宁"
    elif province == "新疆":
        return "新"
    elif province == "西藏":
        return "藏"
    elif province == "香港":
        return "港"
    elif province == "澳门":
        return "澳"
    else:
        return ""